package com.ple.app.user;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapOnTouchListener;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISFeatureLayer;
import com.esri.android.map.event.OnLongPressListener;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.map.CallbackListener;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureEditResult;
import com.esri.core.map.FeatureResult;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.tasks.SpatialRelationship;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
import com.ple.app.jzsf.R;

import com.ple.app.user.DrawGeometryHelper;

import java.util.HashMap;
import java.util.Objects;

/**
 * Created by mcgradytien on 2016/11/21.
 */

public class DrawFarmBoundaryActivity extends Activity {

    private Button btnSaveGeometry;
    private Button btnDrawPolygon;
    private Button btnClearLayer;
    private Button btnUndoBoundary;
    private Button btnBack;
    private Button btnPopupConfirm;
    private Button btnPopupCancel;
    private EditText editTextName;
    private EditText editTextNameEn;

    private boolean isSaved;
    private MapView mMapView;
    private GraphicsLayer graphicsLayer;
    private ArcGISFeatureLayer arcGISFeatureLayer;
    private String featureServicesUrl;
    private SimpleFillSymbol simpleFillSymbol;
    private Polygon polygon = null;
    private QueryParameters queryParameters;
    private Graphic graphic;

    private Feature mFeature = null;

    private String strName;
    private String strNameEN;
    private HashMap<String, Object> h;
    final static String[] geometryType = new String[]{"POINT", "POLYLINE", "POLYGON"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.draw_farm_boundary);

        btnBack = (Button) findViewById(R.id.btn_draw_back);
        btnSaveGeometry = (Button) findViewById(R.id.btn_draw_save);
        btnClearLayer = (Button) findViewById(R.id.btn_draw_clear);
        btnDrawPolygon = (Button) findViewById(R.id.btn_draw_polygon);
        btnUndoBoundary = (Button) findViewById(R.id.btn_draw_undo);
        btnPopupConfirm = (Button) findViewById(R.id.btn_boundary_popup_confirm);
        btnPopupCancel = (Button) findViewById(R.id.btn_boundary_popup_cancel);

        //定义一个简单填充符号
        simpleFillSymbol = new SimpleFillSymbol(Color.BLUE, SimpleFillSymbol.STYLE.SOLID);
        simpleFillSymbol.setAlpha(70);

        mMapView = (MapView) findViewById(R.id.mapView_Boundary);

        //添加ArcGISFeatureLayer 服务用于地图编辑
        featureServicesUrl = "http://192.168.13.99:6080/arcgis/rest/services/china/FeatureServer/0";
        arcGISFeatureLayer = new ArcGISFeatureLayer(featureServicesUrl, ArcGISFeatureLayer.MODE.ONDEMAND);

        mMapView.addLayer(arcGISFeatureLayer);

        graphicsLayer = new GraphicsLayer();
        mMapView.addLayer(graphicsLayer);

        //默认状况下不能保存
        isSaved = false;
        btnSaveGeometry.setEnabled(false);
        btnUndoBoundary.setEnabled(false);

        //Init the helper class for drawing a polygon(farm boundary).
        final DrawGeometryHelper2 drawGeometryHelper2 = new DrawGeometryHelper2(DrawFarmBoundaryActivity.this, mMapView, graphicsLayer, polygon);

        mMapView.setOnTouchListener(drawGeometryHelper2);

        mMapView.setOnLongPressListener(new OnLongPressListener() {
            @Override
            public boolean onLongPress(float v, float v1) {
                if (mMapView.isLoaded()) {
                    Point p = mMapView.toMapPoint(v, v1);
                    /**
                     * 设定queryParameters参数
                     */
                    queryParameters = new QueryParameters();
                    queryParameters.setGeometry(p);
                    queryParameters.setReturnGeometry(true);
                    queryParameters.setInSpatialReference(mMapView.getSpatialReference());
                    queryParameters.setSpatialRelationship(SpatialRelationship.INTERSECTS);

                    QueryAsyncTask q = new QueryAsyncTask(p);
                    q.execute(queryParameters);

                    return true;
                }
                return false;
            }
        });

        //绘面，执行清空操作
        btnDrawPolygon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击开始之后，保存按钮工作
                btnSaveGeometry.setEnabled(true);
                //清空之前的绘制结果
                graphicsLayer.removeAll();
                drawGeometryHelper2.isChoose();
                drawGeometryHelper2.setType(geometryType[2]);
            }
        });

        //保存数据
        btnSaveGeometry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                polygon = drawGeometryHelper2.getPolygon();
                showPopupWindow(v);
            }
        });

        //finish the drawing and  save the polygon.
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DrawFarmBoundaryActivity.this, FarmsInfoInputActivity.class);
                intent.putExtra("state", "边界已完成");
                startActivity(intent);
                finish();//销毁该activity
            }
        });

        /**
         * 清除所画的图层，并设置isChoose 为true，对之前的点进行清空
         */
        btnClearLayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                graphicsLayer.removeAll();
                drawGeometryHelper2.isChoose();
            }
        });

        /**
         * 怕是要被删除了哦！怕是今天不能解决了哦！
         */
        btnUndoBoundary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFeature != null) {
                    //20121222
                    //怕是删除这个操作搞不定哦！
                }
                btnUndoBoundary.setEnabled(false);//关掉删除按钮
            }

        });
    }

    private void showPopupWindow(View view ) {
        //设定自定义的布局作为显示内容
        View popupView = LayoutInflater.from(DrawFarmBoundaryActivity.this).inflate(R.layout.attribute_dialog, null);

        final PopupWindow popupWindow = new PopupWindow(popupView, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_google_signin_btn_icon_dark));

        popupWindow.showAsDropDown(view);
        //popupWindow.showAtLocation(view,2,35,35);

        btnPopupConfirm = (Button) popupView.findViewById(R.id.btn_boundary_popup_confirm);
        btnPopupCancel = (Button) popupView.findViewById(R.id.btn_boundary_popup_cancel);
        editTextName = (EditText) popupView.findViewById(R.id.editText_name);
        editTextNameEn = (EditText) popupView.findViewById(R.id.editText_name_en);


        btnPopupConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                strName = editTextName.getText().toString();
                strNameEN = editTextNameEn.getText().toString();

                h = new HashMap<String, Object>();
                if (strName.length()  !=0  && strNameEN.length() != 0) {
                    /**
                     * Created by mcgradytien on 2016/12/14.
                     * FeatureLayer 数据保存操作
                     * First step：确保加载的地图服务是含有FeatureAccess功能的ArcGISFeatureLayer服务。
                     * Second step:新建Geometry对象，GeometryEngine.simplify()这个方法还需细细揣摩，
                     *             添加自己绘制的Polygon
                     * Third step: 新建Graphic对象，用于存储geometry对象
                     * Forth step：采用applyEdit()方法，将结果更新
                     * 还有一些方法不熟悉，需要多看看，目前只是将结果保存了，但是geometry对象不带有属性信息
                     */
                    h.put("NAME", (Object) strName);
                    h.put("NAMEEN",(Object)strNameEN);
                    Graphic g = new Graphic(polygon, simpleFillSymbol, h);
                    arcGISFeatureLayer.applyEdits(new Graphic[]{g}, null, null, new CallbackListener<FeatureEditResult[][]>() {
                        @Override
                        public void onCallback(FeatureEditResult[][] featureEditResults) {
                            Log.i("Saving", "Saving");
                        }

                        @Override
                        public void onError(Throwable throwable) {

                        }
                    });
                    Toast.makeText(DrawFarmBoundaryActivity.this,"信息录入成功！",Toast.LENGTH_LONG).show();
                    graphicsLayer.removeAll();
                    popupWindow.dismiss();

                } else {
                    Toast.makeText(DrawFarmBoundaryActivity.this, "请将信息补全!", Toast.LENGTH_LONG).show();
                }

                btnSaveGeometry.setEnabled(false);

            }
        });

        btnPopupCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Toast.makeText(DrawFarmBoundaryActivity.this, "取消数据录入", Toast.LENGTH_LONG).show();
            }
        });

    }

    /**
     * 新开线程处理查询事件
     */
    private class QueryAsyncTask extends AsyncTask<QueryParameters, Void, FeatureResult> {
        private QueryTask queryTask;
        private Point anchorPoint;
        private SimpleFillSymbol simpleFillSymbol;

        QueryAsyncTask(Point p) {
            anchorPoint = p;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            queryTask = new QueryTask(featureServicesUrl);

            //指定一个填充符号

            simpleFillSymbol = new SimpleFillSymbol(Color.YELLOW);
            simpleFillSymbol.setAlpha(60);
        }

        @Override
        protected FeatureResult doInBackground(QueryParameters... params) {
            FeatureResult featureResult = null;

            if (params[0] != null && params.length > 0) {
                queryParameters = params[0];
                try {
                    featureResult = queryTask.execute(queryParameters);
                    return featureResult;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(FeatureResult objects) {
            //super.onPostExecute(objects);
            graphicsLayer.removeAll();//清空已经选择的图层

            if (objects != null && objects.featureCount() > 0) {
                for (Object o : objects) {
                    Feature feature = (Feature) o;
                    //将查询到的结果显示到地图中去
                    graphic = new Graphic(feature.getGeometry(), simpleFillSymbol, feature.getAttributes());
                    graphicsLayer.addGraphic(graphic);

                    btnUndoBoundary.setEnabled(true);//删除按钮启用

                }
            }
            return;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}